package com.yang.my.coon.one;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * wait notifiy方法; wait释放锁,notfiy不释放锁
 *
 * @Author: Mu_YI
 * @Date: 2019/3/18 23:18
 * @Version 1.0
 */
public class ListAddTwo {

    private volatile static List list = new ArrayList();

    public void add() {
        list.add("hhhh");
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {

        final ListAddTwo listAddTwo = new ListAddTwo();

        final Object lock = new Object();

        final CountDownLatch countDownLatch = new CountDownLatch(1);

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (lock) {
                        for (int i = 0; i <= 10; i++) {
                            listAddTwo.add();
                            System.out.println("当前线程：" + Thread.currentThread().getName() + "添加了一个元素..");
                            Thread.sleep(500);
                            if (listAddTwo.size() == 5) {
                                System.out.println("已经发出通知");
                                lock.notify();
                                // countDownLatch.countDown();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    try {
                        if (listAddTwo.size() == 5) {
                            System.out.println("t2进入...");
                            lock.wait();
                            // countDownLatch.await();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("当前线程:" + Thread.currentThread().getName() + "收到通知停止线程");
                throw new RuntimeException();
            }
        }, "t2");

        t1.start();
        t2.start();

    }

}
